$(function() {
  class Register {
    constructor() {
      this.init();
    }
    init() {
      this.initDom();
      this.bindEvent();
    }
    initDom() {
      //获取用户名框
      this.username = $('#username');
      //获取昵称框
      this.nickname = $('#nickname');
      //获取密码框
      this.password = $('#password');
      //获取确认密码框
      this.cpassword = $('#cpassword');
      //获取注册按钮
      this.register_btn = $('#register-btn');
    }
    bindEvent() {
      this.register_btn.on('click', () => {
        this.sendRegister();
      });
    }
    //发送注册请求
    sendRegister() {
      axios({
        method: 'POST',
        url: 'http://127.0.0.1:8888/users/register',
        data: formData({
          username: this.username.val(),
          nickname: this.nickname.val(),
          password: this.password.val(),
          rpassword: this.cpassword.val()
        })
      }).then(res => {
        if(res.data.code === 1) {
          this.storeUserInfo();
          new Toast({
            message: res.data.message,
            color: '#67C23A',
            callback() {
              location.href = './login.html';
            }
          });
        }else {
          new Toast({
            message: res.data.message,
            color: '#F56C6C'
          });
        }
      })
    }
    //session本地存储用户名密码传递到登录页
    storeUserInfo() {
      let obj = {
        username: this.username.val(),
        password: this.password.val()
      }
      sessionStorage.setItem('userInfo', JSON.stringify(obj));
    }
  }
  new Register();
})